<template>
  <div>
    <el-form ref="myform" :model="formItem" :rules="rules" label-width="auto" size="mini">
      {{range $i, $v := .Fields}}<el-form-item label="{{$v.TableFieldComment}}" prop="text">
        <el-input v-model="formItem.text" placeholder="请输入{{$v.TableFieldComment}}" />
      </el-form-item>
      {{end}}
    </el-form>
  </div>
</template>

<script>
import {
  create,
  update,
  detail
} from '@neu/dcam-ui/api/{{.LowerClassName}}'

import { list } from '@neu/dcam-ui/api/{{.LowerClassName}}.js'
// 定义一个表单原始项
const formItem = {
  type: '',
  code: '',
  text: ''
  // ,
  // sort: ''
}
export default {
  name: '{{.ClassName}}EditForm',
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      // 编辑的表单内容
      formItem: {
        ...formItem
      },
      // 表单验证规则
      rules: {
        type: [{
          required: true,
          message: '码表类型不能为空',
          trigger: 'blur'
        }],
        code: [{
          required: true,
          message: '码表编码不能为空',
          trigger: 'blur'
        }],
        text: [{
          required: true,
          message: '码表文本不能为空',
          trigger: 'blur'
        }]
        // ,
        // sort: [{
        //   required: true,
        //   message: '顺序不能为空',
        //   trigger: 'blur'
        // },
        // {
        //   validator: function(rule, value, callback) {
        //     if (/^[0-9]*$/.test(value) === false) {
        //       callback(new Error('请输入正确的数字'))
        //     } else {
        //       callback()
        //     }
        //   },
        //   trigger: 'blur'
        // }
        // ]
      },
      modal: true
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: function() {
      this.fetch()
    }
  },
  created() {
    this.fetch()
    list().then(response => {
      this.dictionaryType = response.data
    })
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          this.formItem = {
            ...response.data
          }
        })
      } else {
        this.formItem = {
          ...formItem
        }
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            if (updated) {
              resolve(update(this.id, this.formItem))
            } else {
              resolve(create(this.formItem))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.myform.resetFields()
    }
  }
}
</script>
